const startList = ['Filter For A City', 'Or A State'];
const resultArray = [];
const resourceWithCities = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
let timeoutId = undefined;
const listEl = document.querySelector('.list-result');

const getCities = async () => {
    const resp = await fetch(resourceWithCities);
    const data = await resp.json();
    
    return data;
}

const filterWithRegExp = (searchValue, checkedValue) => {
    const regExp = new RegExp(searchValue, 'gi');
    return checkedValue.match(regExp);
}

const renderList = (itemsList) => {
    listEl.innerHTML = '';

    for (const item of itemsList) {
        const newItem = document.createElement('li');
        
        if (typeof item === 'string') {
            newItem.innerHTML = item;
        } else {
            newItem.innerHTML = item.city + ', ' + item.state;
        }

        
        listEl.appendChild(newItem);
    }

    setTimeout(() => {
        listEl.classList.remove('close');
    }, 500);
}

function searchHandler() {
    if (timeoutId) clearTimeout(timeoutId);

    listEl.classList.add('close');

    timeoutId = setTimeout(async () => {
        if (!resultArray.length) {
            const cities = await getCities();
            resultArray.push(...cities)
        }
        
        const newList = resultArray.filter((item) => {
            console.log(`city ${item.city}, state ${item.state}`, filterWithRegExp(this.value, item.city) || filterWithRegExp(this.value, item.state));

            return Boolean(filterWithRegExp(this.value, item.city) || filterWithRegExp(this.value, item.state));
        });

        renderList(newList);
    }, 1000);
}

renderList(startList);

document.querySelector('.search-list__search-block input[name="search_text"]').addEventListener('keyup', searchHandler);